import datetime
import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from house.models import Area, House, HouseImage
from house.utils import guolv, sousuo
from libs.qiniuyun.qiniu_storage import storage, QINIUYUN_URL
from order.models import Order
from users.models import User
from users.utils import LoginRequiredMixin

"""城区列表"""
class AreasListView(View):
    """城区列表"""
    def get(self, request):
        areas = Area.objects.all()
        data = [{'aid':area.id, 'aname':area.name} for area in areas]
        return JsonResponse({
            'errmsg':'获取成功',
            'errno':'0',
            'data':data
        })




"""发布&搜索"""
class ReleaseHouse(View):

    """发布"""
    def post(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({
                'errmsg': '用户未登录',
                'errno': '4101'
            })
        # 接收参数
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')  # 标题
        price = json_dict.get('price')  # 价格
        area_id = json_dict.get('area_id')  # 城区id
        address = json_dict.get('address')  # 房屋地址
        room_count = json_dict.get('room_count')  # 房屋数目
        acreage = json_dict.get('acreage')  # 房屋面积
        unit = json_dict.get('unit')  # 几室几厅
        capacity = json_dict.get('capacity')  # 房屋容纳的人数
        beds = json_dict.get('beds')  # 配置
        deposit = json_dict.get('deposit')  # 押金
        min_days = json_dict.get('min_days')  # 最少时间
        max_days = json_dict.get('max_days')  # 最大时间
        # 用户选择的设施信息id列表，如：[7, 8]
        facility = json_dict.get('facility')
        if not all([title, price, area_id, address,
                    room_count, acreage, unit,
                    capacity, beds, deposit,
                    min_days, max_days]):
            return JsonResponse({
                'errmsg': '参数错误',
                'errno': '4103',
            })
        try:
            # 储存房屋信息并获得房屋对象
            house = House.objects.create(
                user_id=request.user.id,
                title=title, price=price,
                area_id=area_id, address=address,
                room_count=room_count, acreage=acreage, unit=unit,
                capacity=capacity, beds=beds, deposit=deposit,
                min_days=min_days, max_days=max_days, )
            house.facility.set(facility)
            house.save()
        except:
            return JsonResponse({'errmsg': "数据库查询错误",
                                 'errno': "4001"})

        return JsonResponse({"errno": "0",
                             "errmsg": "发布成功",
                             "data": {"house_id": house.id}})

    """搜索"""
    def get(self, request):
        aid = request.GET.get('aid')    # 城区id
        sd = request.GET.get('sd')  # 开始日期
        ed = request.GET.get('ed')  # 结束日期
        sk = request.GET.get('sk')  # 排序方式
        p = request.GET.get('p')    # 页数

        # 判断分页信息
        if not p:
            # 如果没有值，默认1
            p = 1
        # 判断排序方式
        if sk == 'booking':
            sk = '-order_count'
        elif sk == 'price-inc':
            sk = 'price'
        elif sk == 'price-des':
            sk = '-price'
        elif sk == 'new':
            sk = '-create_time'
        return sousuo(aid, sd, ed, p, sk)



# 发布图片
class HouseImageView(LoginRequiredMixin, View):
    def post(self, request, house_id):
        img = request.FILES.get('house_image', None)
        if img:
            img_url = storage(img.read())
            avatar_url = QINIUYUN_URL + img_url
            # print(avatar_url)
            # print(img_url, type(img_url))
            house = House.objects.get(id=house_id)
            house.index_image_url = img_url
            house.save()
            date = {"url": avatar_url}
            return JsonResponse({"data": date,
                                 "errno": "0",
                                 "errmsg": "图片上传成功"})
        else:
            return JsonResponse({
                "errno": "4301",
                "errmsg": "空文件"
            })

"""我的房屋列表"""
class MyHouse(LoginRequiredMixin, View):
    def get(self, request):
        user_id = request.user.id
        houses = House.objects.filter(user=user_id)
        list1 = []
        for house in houses:
            list1.append({
                'address':house.address,
                'area_name':Area.objects.get(id=house.area_id).name,
                'ctime':house.create_time,
                'house_id':house.id,
                'img_url':QINIUYUN_URL+str(house.index_image_url),
                'order_count':house.order_count,
                'price':house.price,
                'room_count':house.room_count,
                'title':house.title,
                'user_avatar':QINIUYUN_URL + str(request.user.avatar)
            })
        return JsonResponse({
            'data':{'houses':list1},
            'errmsg':'ok',
            'errno':'0'
        })

"""首页推荐"""
class HousesIndex(View):
    """首页推荐"""
    def get(self, request):
        houses = House.objects.all()[0: 3]
        list1 = [{
            'house_id':house.id,
            'img_url':QINIUYUN_URL + str(house.index_image_url),
            'title':house.title
        } for house in houses]

        return JsonResponse({
            'data':list1,
            'errmsg':'ok',
            'errno':'0'
        })

"""房屋详情"""
class HouseView(View):
    """房屋详情"""

    def get(self, request, house_id):
        if request.user.is_authenticated:
            user_id = request.user.id
        else:
            user_id = -1
        try:
            house = House.objects.get(id=house_id)
        except:
            return JsonResponse({
                'errmsg': '数据库查询错误',
                'errno': '4002'
            })

        comment_list = [] # 评论列表
        orders = Order.objects.filter(house_id=house_id)
        for order in orders:
            comment_list.append({
                'comment': order.comment,
                'ctime': order.update_time,
                'user_name': User.objects.get(id=order.user_id).username
            })

        facilities_list = [] # 设施信息id列表
        for facilities in house.facility.all():
            facilities_list.append(facilities.id)

        img_urls_list = []
        for img in HouseImage.objects.filter(house_id=house_id):
            img_urls_list.append(QINIUYUN_URL + str(img.url))


        data = {
            'house':{
                'acreage':house.acreage,    # 房屋面积
                'address':house.address,   # 房屋地址
                'beds':house.beds,  # 房屋床铺的配置
                'capacity':house.capacity,  # 房屋容纳的人数
                'comment':comment_list,
                'deposit':house.deposit,   # 房屋押金
                'facilities':facilities_list,    # 设施信息id列表
                'hid':house.id,
                'img_urls':img_urls_list,  # 房屋图片列表
                'max_days':house.max_days,
                'min_days':house.min_days,
                'price':house.price,
                'room_count':house.room_count,
                'title':house.title,
                'unit':house.unit,  # 几室几厅
                'user_avatar':QINIUYUN_URL + str(User.objects.get(id=house.user_id).avatar), # 房东头像,
                'user_id':house.user_id,   # 房东ID
                'user_name':User.objects.get(id=house.user_id).username  # 房东name
            },
            'user_id':user_id
        }
        return JsonResponse({
            'data':data,
            'errmsg':'ok',
            'errno':'0'
        })

